﻿/**
* CRL
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRL.Core;
using Quartz;
using CRL.Core.Remoting.WorkConsole;
using TaskStatus = CRL.Core.Remoting.WorkConsole.TaskStatus;

namespace CRL.QuartzScheduler
{
    /// <summary>
    /// 任务接口
    /// 优先使用Cron表达式,如果为空,则使用重复规则
    /// </summary>
    [DisallowConcurrentExecution]
    public abstract class QuartzJob : TriggerData, IJob
    {
        /// <summary>
        /// 执行的任务委托
        /// </summary>
        public abstract void DoWork();
        //static object lockObj = new object();
        protected void Log(string message)
        {
            var name = GetType().Name;
            string logName = string.Format("Task_{0}", name);
            EventLog.Log(message, logName);
            Console.WriteLine(message);
        }
        Task IJob.Execute(IJobExecutionContext context)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            string errorMsg = "";
            try
            {
                QuartzWorker.instance.taskManage?.UpdateTaskStatus(context.JobDetail.Key.Name, TaskStatus.Runing, 0, "");
                var data = context.JobDetail.JobDataMap["TagData"];
                TagData = data;
                var a = context.JobDetail.JobDataMap.TryGetValue("CustomFunc", out var func);
                if (a)
                {
                    CustomFunc = func as Action<object>;
                }
                DoWork();
            }
            catch (Exception ero)
            {
                Log("执行出错:" + ero);
                errorMsg = ero.Message;
            }
            sw.Stop();
            try
            {
                QuartzWorker.instance.taskManage?.UpdateTaskStatus(context.JobDetail.Key.Name, TaskStatus.Wait, sw.ElapsedMilliseconds, errorMsg);
            }
            catch { }
            //QuartzWorker.workCache[name] = false;
            return Task.FromResult(0);
        }
    }


    class _CustomWork : QuartzJob
    {
        public _CustomWork()
        {

        }
        public override void DoWork()
        {
            CustomFunc?.Invoke(TagData);
        }
    }

}
